package de.koller.world;

import de.koller.million.enc.network.Connection;
import de.koller.million.enc.network.NetPackage;
import de.koller.million.enc.network.netpack.Packs;
import de.koller.million.enc.network.netpack.TimeSync;
import de.koller.oceanFramework.gl.OceanGame;
import de.koller.oceanFramework.thread.buffer.Buffer;
import de.koller.oceanFramework.tree.Child;
import de.koller.oceanFramework.tree.Sea3X;
import de.koller.world.render.WorldRender;

public class WorldRoot extends Sea3X {

	private long latency = 0;
	
	private Connection connection;
	@Child public final WorldRender worldRender = new WorldRender();
			
	@Override
	protected void init() {
		super.init();
		
		this.setIgnoreChildRender( true );
		connection = Connection.startConnection( ((OceanGame)this.getGame()).getIp() );
	}

	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		Buffer<Object> b = connection.getReceived();
		while( !b.isEmpty() ) {
			NetPackage p = (NetPackage)b.pop();
			if( p.getPack() == Packs.TimeSync )
				setTime( (TimeSync)p );
		}
	}

	@Override
	protected void render( int elapsedTime ) {
		super.render( elapsedTime );
		
		worldRender.renderSzene();
	}
	
	public void setTime( TimeSync sync ) {
		this.latency = System.currentTimeMillis() - sync.timeStamp; 
	}

	public long getLatency() {
		return latency;
	}
	
}
